package com.huaqin.punan;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity {
	public static final String TAG = "AutoDialerMain";
	public static final String PREFERENCES_AUTO_DIALER = "PreferencesAutoDialer";
	public static final int REDIALER_ON_DISCONNECT = 0;
	public static final int REDIALER_EVERY_FIVE_MINUTES = 1;
	public static final int REDIALER_EVERY_TEN_MINUTES = 2;
	private static final int CONTACT_PICKER_RESULT = 1001;

	private RadioGroup mRadioGroup;
	private RadioButton mRadioButton1;
	private RadioButton mRadioButton2;
	private RadioButton mRadioButton3;
	private EditText mEditText;
	private ImageButton mImageButton;
	private Button mButton;
	
	private boolean startflag = false;
	public static int reDialerType = 0 ;
	public static String contactName = "";
	public static String phoneNum = "";
	
	SharedPreferences phoneNumPreference;
	TelephonyManager mTelephonyManager;
	Timer timer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mTelephonyManager = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE);
		mTelephonyManager.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
		
		phoneNumPreference = getSharedPreferences(PREFERENCES_AUTO_DIALER,Context.MODE_PRIVATE);
		final SharedPreferences.Editor editor = phoneNumPreference.edit();
		
		mRadioGroup = (RadioGroup)findViewById(R.id.myradiogroup);
		mRadioButton1 = (RadioButton)findViewById(R.id.radiobtn1);
		mRadioButton2 = (RadioButton)findViewById(R.id.radiobtn2);
		mRadioButton3 = (RadioButton)findViewById(R.id.radiobtn3);
		mEditText = (EditText)findViewById(R.id.et1);
		mImageButton = (ImageButton)findViewById(R.id.imagebtn1);
		mButton = (Button)findViewById(R.id.btn1);
		
		reDialerType = phoneNumPreference.getInt("auto_dialer_type", 0);
		phoneNum = phoneNumPreference.getString("auto_dialer_num", "");
		
		if(reDialerType == 0){
			mRadioButton1.setChecked(true);
		}else if(reDialerType == 1){
			mRadioButton2.setChecked(true);
		}else if(reDialerType == 2){
			mRadioButton3.setChecked(true);
		}
		
		if(phoneNum != null && !("".equals(phoneNum))){
			mEditText.setText(phoneNum);
		}
		
		mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch(checkedId){
				case R.id.radiobtn1:
					reDialerType = REDIALER_ON_DISCONNECT;
					break;
				case R.id.radiobtn2:
					reDialerType = REDIALER_EVERY_FIVE_MINUTES;
					break;
				case R.id.radiobtn3:
					reDialerType = REDIALER_EVERY_TEN_MINUTES;
					break;
				default:
					reDialerType = REDIALER_ON_DISCONNECT;
					break;
				}
				
				editor.putInt("auto_dialer_type", reDialerType);
				editor.commit();
			}});
		
		mButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				phoneNum = mEditText.getText().toString().trim();
				editor.putString("auto_dialer_num", phoneNum);
				editor.commit();
				
				if(!startflag){
					
					if("".equals(phoneNum) || phoneNum == null){
						Toast.makeText(MainActivity.this, "请输入电话号码", Toast.LENGTH_SHORT).show();
					}else{
						startflag = true;
						MakePhoneCall();
					}
					
					if(reDialerType != REDIALER_ON_DISCONNECT){
						timer = new Timer();
						timer.schedule(new TimerTask(){
							@Override
							public void run() {
								// TODO Auto-generated method stub
								MakePhoneCall();
							}
						}, 2000, 5*60*1000*reDialerType);
					}
					
					mButton.setText(R.string.btn1_dial_stop);
				}else{
					if(timer != null){
						timer.cancel();
					}
					startflag = false;
					mButton.setText(R.string.btn1_dial_start);
				}
				
			}});
		
		mImageButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,	ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
			}});
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode){
	        case (CONTACT_PICKER_RESULT) :
	        	if (resultCode == Activity.RESULT_OK){
	        		Uri contactData = data.getData();
	 				Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
	 				while(cursor.moveToNext()){
	 					String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
	 			        contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
	 			        String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
	 			        
	 			        if ( hasPhone.equalsIgnoreCase("1"))
	 			            hasPhone = "true";
	 			        else
	 			            hasPhone = "false" ;
	 			       
	 			        if (Boolean.parseBoolean(hasPhone)){
	 			        	Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
	 			        	while (phones.moveToNext()){
	 			        	phoneNum = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
	 			        }
	 			        phones.close();
	 			        
	 			        mEditText.setText(phoneNum);
	 			        
	 			        /**
	 			         * Other Info Not Used
	 			         */
	 			        /*
	 			        // Find Email Addresses
	 			        Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
	 			        while (emails.moveToNext()){
	 			        	String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
	 			        }
	 			        emails.close();
	 			        
	 			        //Find Address Info
	 			        Cursor address = getContentResolver().query(
	 			                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
	 			                null,
	 			                ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
	 			                null, null);
	 			        while (address.moveToNext()){ 
	 			        	// These are all private class variables, don't forget to create them.
	 			        	String poBox      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
	 			        	String street     = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
	 			        	String city       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
	 			        	String state      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
	 			        	String postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
	 			        	String country    = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
	 			        	String type       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
	 			        }  //address.moveToNext()   
	 			        */
	 			        }
	 			       
	 				}
	 			Log.d(TAG, "Result_name="+contactName);
	 			Log.d(TAG, "Result_num="+phoneNum);
	        	}
	        break;
	    }
	 
	}




	class MyPhoneStateListener extends PhoneStateListener {

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			switch(state){
			case TelephonyManager.CALL_STATE_IDLE:
				Log.d(TAG, "===>>CALL_STATE_IDLE");
				if(startflag && reDialerType == REDIALER_ON_DISCONNECT){
					try {
						Thread.sleep(3000);
						MakePhoneCall();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				break;
				
			case TelephonyManager.CALL_STATE_RINGING:
				Log.d(TAG, "===>>CALL_STATE_RINGING");
				break;
				
			case TelephonyManager.CALL_STATE_OFFHOOK:
				Log.d(TAG, "===>>CALL_STATE_OFFHOOK");
				break;
			}
			
			super.onCallStateChanged(state, incomingNumber);
		}
	}
	
	private void MakePhoneCall(){
		Uri phoneUri = Uri.parse("tel:"+phoneNum);
		Intent call_intent = new Intent(Intent.ACTION_CALL, phoneUri);
		call_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(call_intent);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		//Toast.makeText(MainActivity.this, "featureId="+featureId+",itemid="+item.getItemId(), Toast.LENGTH_LONG).show();
		switch(item.getItemId()){
		case R.id.menu_settings:
			Toast.makeText(MainActivity.this, "not completement", Toast.LENGTH_SHORT).show();
			break;
		case R.id.menu_about:
			Dialog alertDialog =new AlertDialog.Builder(this)
				.setTitle("About")
				.setIcon(R.drawable.ic_launcher)
				.setMessage("Writen By Punan. \nThanks for You Choose AutoDialler")
				.create();
			alertDialog.show();
			break;
		}
		
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onOptionsMenuClosed(Menu menu) {
		// TODO Auto-generated method stub
		super.onOptionsMenuClosed(menu);
		Toast.makeText(MainActivity.this, "onOptionsMenuClosed", Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
}
